Authenticate User using Tokens

{ authenticateUserByToken }

Generates an access authentication token for a given user without their password, using an administrative token to authorize login to the application instead.

Method

/API2/auth/authenticateUserByToken

  • API Section: /API2/auth
  • API Version: 2.0
  • From Release: 2018.5
  • Method operates via POST actions only.
  • Input Parameters

    Name

    userTokenCredentials

    Object Type

    Description

    The user credentials for authentication by token.

    Output Response

    Successful Result Code

    200

    Description of Response Type

    The response is the security token as a base64 string. It is usually stored in a cookie.

    Notes

    The security token is an authentication token that needs to be first generated by an administrative user with full credentials first.When saved as a cookie in a web browser, it can then be used to auto-login the user into the application.

    Examples
    User Client Authentication (C#):

    This example demonstrates how to authenticate users for the main application.

    using System;
    using System.Linq;
    using System.Web;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    using System.Net.Http;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace CsWebSite
    {
    	public partial class Default : System.Web.UI.Page
    	{
    		public const String API_PATH = "http://mySite.com/API2/";
    		protected void Page_Load(object sender, EventArgs e)
    		{
    			//logging the user
    			String adminToken = getToken("authenticateUser", new
    			{ 	data = new {
    					userName = "adminUser1",
    					password = "abc123!"
    				}
    			});
    
    			String userToken = getToken("authenticateUserByToken", new
    			{ 	data = new {
    					userIdentity = "userName",
    					token = adminToken
    				}
    			});
    			//this cookie should be placed on the domain pyramid is installed on - mySite.com in this example
    			Response.Cookies.Add(new HttpCookie("PyramidAuth", userToken));
    
    
    		}
    
    	//generic method for getting the token via REST
    		private String getToken(String service, Object data)
    		{
    			HttpClient client = new HttpClient();
    
    			StringContent content = null;
    			content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
    			Task<HttpResponseMessage> response = client.PostAsync(API_PATH + "auth/" + service, content);
    
    			return response.Result.Content.ReadAsStringAsync().Result;
    		}
    		
    
    	}
    }
    
    		
    User Client Authentication (Java):

    This example demonstrates how to authenticate users for the main application.

    import com.sun.net.httpserver.HttpExchange;
    import com.sun.net.httpserver.HttpHandler;
    import com.sun.net.httpserver.HttpServer;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.BasicResponseHandler;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClientBuilder;
    import org.json.simple.JSONObject;
    
    import java.io.IOException;
    import java.net.InetSocketAddress;
    
    public class Main {
    	private static final String pyramidPath = "http://mySite.com/API2/";
    
    	public static void main(String[] args) throws IOException {
    		HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
    		server.createContext("/login", new LoginHandler());
    
    
    		server.setExecutor(null); // creates a default executor
    		server.start();
    
    	}
    
    	private static class LoginHandler implements HttpHandler {
    		@Override
    		public void handle(HttpExchange httpExchange) throws IOException {
    			//logging the user
    			JSONObject adminCredentials = new JSONObject();
    			adminCredentials.put("userName", "testUser1");
    			adminCredentials.put("password", "abc456!");
    			String adminToken = getToken("authenticateUser", adminCredentials);
    
    			//logging the user in using the admin's token
    			JSONObject userCredentials = new JSONObject();
    			userCredentials.put("userIdentity", "test.user1@mySite.com");
    			userCredentials.put("token", adminToken);
    
    			String userToken = getToken("authenticateUserByToken", userCredentials);
    
    			//searching the user by name 
    			JSONObject getUsersByName = new JSONObject();
    			getUsersByName.put("userName", "testUser1");
    			getUsersByName.put("auth", adminToken);
    			JSONObject results = callApi("access/getUsersByName", getUsersByName);
    			String userId = ((JSONObject) ((JSONArray) results.get("data")).get(0)).get("id").toString();
    
    			//reading the user's private folder
    			JSONObject getFolderItems = new JSONObject();
    			getFolderItems.put("folderId", userId);//the user private folder id is the same as the user id
    			getFolderItems.put("auth", adminToken);
    			JSONObject privateFolder = callApi("content/getFolderItems", getFolderItems);
    			String messageStr = "private folder id is " + userId + " and it contains ";
    			JSONArray folderContent = ((JSONArray) privateFolder.get("data"));
    			for (int i = 0; i < folderContent.size(); ++i) {
    				messageStr += ((JSONObject) folderContent.get(i)).get("caption") + ",";
    			}
    
    			byte[] message = messageStr.getBytes(StandardCharsets.UTF_8);
    			httpExchange.getResponseHeaders().add("Set-Cookie", "PyramidAuth=" + userToken);
    			httpExchange.sendResponseHeaders(200, message.length);
    			httpExchange.getResponseBody().write(message);
    		}
    	}
    
    
    	protected static String getToken(String service, JSONObject data) throws IOException {
    		JSONObject dataHolder = new JSONObject();
    		dataHolder.put("data", data);
    		return sendPost("auth/" + service, dataHolder.toJSONString());
    	}
    
    
    	protected static String sendPost(String path, String data) throws IOException {
    		try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
    
    			String address = pyramidPath + path;
    			HttpPost request = new HttpPost(address);
    			StringEntity params = new StringEntity(data);
    			request.addHeader("content-type", "application/x-www-form-urlencoded");
    			request.setEntity(params);
    			CloseableHttpResponse response = httpClient.execute(request);
    			return new BasicResponseHandler().handleResponse(response);
    		}
    	}
    }